import time

import redis

from utils.logger_helper import LoggerHelper

app_name = "redis_expire_test"
logger = LoggerHelper.get_logger(logger_name=app_name)


class RedisExpireTest(object):
    def __init__(self):
        self.redis_pool_1 = redis.ConnectionPool(
            host="l-redis692.dba.cn6", port="17195", db=0,
            password="3f4e48ff", max_connections=2
        )
        self.redis_pool_2 = redis.ConnectionPool(
            host="l-redis424.dba.cn1", port="17196", db=0,
            password="3f4e48ff", max_connections=2
        )

    def _get_redis_connection_1(self):
        """
        从Redis Pool中获取连接，避免重复建立Redis连接
        :return:
        """
        return redis.Redis(connection_pool=self.redis_pool_1, decode_responses=True)

    def _get_redis_connection_2(self):
        """
        从Redis Pool中获取连接，避免重复建立Redis连接
        :return:
        """
        return redis.Redis(connection_pool=self.redis_pool_2, decode_responses=True)

    def run_test(self):
        logger.info("开始导入数据")
        redis_conn_1 = self._get_redis_connection_1()
        redis_conn_2 = self._get_redis_connection_2()
        loop_times = 1000000
        loop_index = 0
        logger.info("开始导入SMALL KEY数据")
        while loop_index < loop_times:
            sm_key_name = "dba:sm_key_{}".format(loop_index)
            redis_conn_1.setex(name=sm_key_name, time=24 * 3600 * 2, value=loop_index)
            if loop_index % 100 == 0:
                logger.info("完成进度:{}%".format(round(loop_index * 100 / loop_times, 2)))
            loop_index += 1
        loop_times = 1000000
        loop_index = 0
        lg_key_value = "*" * 10000
        logger.info("开始导入LARGE KEY数据")
        while loop_index < loop_times:
            lg_key_name = "dba:lg_key_{}".format(loop_index)
            redis_conn_1.setex(name=lg_key_name, time=300, value=lg_key_value)
            redis_conn_2.setex(name=lg_key_name, time=300, value=lg_key_value)
            if loop_index % 100 == 0:
                logger.info("完成进度:{}%".format(round(loop_index * 100 / loop_times, 2)))
            loop_index += 1
            time.sleep(0.01)
        pass


def init_logger():
    LoggerHelper.init_logger(logger_name=app_name)
    global logger
    logger = LoggerHelper.get_logger(logger_name=app_name)


def test_task():
    ret = RedisExpireTest()
    ret.run_test()


if __name__ == '__main__':
    init_logger()
    test_task()
